<template>
  <div class="attribute-policies-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <span>属性策略管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加策略
          </el-button>
        </div>
      </template>

      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索策略名称"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <el-table
        :data="filteredPolicies"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="策略名称" width="150" />
        <el-table-column prop="attributeKey" label="属性键" width="150" />
        <el-table-column prop="attributeValue" label="属性值" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" @click="showRoleDialog(row)">角色</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑策略对话框 -->
    <el-dialog
      v-model="policyDialogVisible"
      :title="isEdit ? '编辑策略' : '添加策略'"
      width="500px"
    >
      <el-form
        ref="policyFormRef"
        :model="policyForm"
        :rules="policyRules"
        label-width="100px"
      >
        <el-form-item label="策略名称" prop="name">
          <el-input v-model="policyForm.name" />
        </el-form-item>
        <el-form-item label="属性键" prop="attributeKey">
          <el-input v-model="policyForm.attributeKey" />
        </el-form-item>
        <el-form-item label="属性值" prop="attributeValue">
          <el-input v-model="policyForm.attributeValue" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="policyForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="policyForm.status" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="policyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePolicy" :loading="saving">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="500px"
    >
      <el-checkbox-group v-model="selectedRoles">
        <el-checkbox
          v-for="role in allRoles"
          :key="role.id"
          :label="role.id"
        >
          {{ role.name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRoles" :loading="savingRoles">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { attributePolicyApi } from '@/api/attributePolicy'

export default {
  name: 'AttributePolicies',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const savingRoles = ref(false)
    const policies = ref([])
    const allRoles = ref([])
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    const policyDialogVisible = ref(false)
    const roleDialogVisible = ref(false)
    const isEdit = ref(false)
    const currentPolicy = ref(null)
    const selectedRoles = ref([])

    const policyForm = reactive({
      name: '',
      attributeKey: '',
      attributeValue: '',
      description: '',
      status: 'active'
    })

    const policyRules = {
      name: [
        { required: true, message: '请输入策略名称', trigger: 'blur' }
      ],
      attributeKey: [
        { required: true, message: '请输入属性键', trigger: 'blur' }
      ],
      attributeValue: [
        { required: true, message: '请输入属性值', trigger: 'blur' }
      ]
    }

    const filteredPolicies = computed(() => {
      if (!searchKeyword.value) return policies.value
      return policies.value.filter(policy => 
        policy.name.includes(searchKeyword.value) ||
        policy.attributeKey.includes(searchKeyword.value)
      )
    })

    const loadPolicies = async () => {
      loading.value = true
      try {
        // 模拟API调用
        const mockPolicies = [
          {
            id: 1,
            name: '部门策略',
            attributeKey: 'department',
            attributeValue: 'IT部门',
            description: 'IT部门用户策略',
            status: 'active',
            createTime: '2024-01-01 10:00:00'
          },
          {
            id: 2,
            name: '地区策略',
            attributeKey: 'region',
            attributeValue: '北京',
            description: '北京地区用户策略',
            status: 'active',
            createTime: '2024-01-02 10:00:00'
          },
          {
            id: 3,
            name: '级别策略',
            attributeKey: 'level',
            attributeValue: '高级',
            description: '高级用户策略',
            status: 'active',
            createTime: '2024-01-03 10:00:00'
          }
        ]
        policies.value = mockPolicies
        total.value = mockPolicies.length
      } catch (error) {
        ElMessage.error('加载策略列表失败')
      } finally {
        loading.value = false
      }
    }

    const loadRoles = async () => {
      try {
        // 模拟角色数据
        allRoles.value = [
          { id: 1, name: '管理员' },
          { id: 2, name: '教师' },
          { id: 3, name: '学生' }
        ]
      } catch (error) {
        ElMessage.error('加载角色列表失败')
      }
    }

    const showAddDialog = () => {
      isEdit.value = false
      Object.assign(policyForm, {
        name: '',
        attributeKey: '',
        attributeValue: '',
        description: '',
        status: 'active'
      })
      policyDialogVisible.value = true
    }

    const showEditDialog = (policy) => {
      isEdit.value = true
      currentPolicy.value = policy
      Object.assign(policyForm, {
        name: policy.name,
        attributeKey: policy.attributeKey,
        attributeValue: policy.attributeValue,
        description: policy.description,
        status: policy.status
      })
      policyDialogVisible.value = true
    }

    const showRoleDialog = (policy) => {
      currentPolicy.value = policy
      selectedRoles.value = [1, 2] // 模拟已选角色
      roleDialogVisible.value = true
    }

    const handleSavePolicy = async () => {
      try {
        await policyFormRef.value.validate()
        saving.value = true
        
        if (isEdit.value) {
          ElMessage.success('策略更新成功')
        } else {
          ElMessage.success('策略创建成功')
        }
        
        policyDialogVisible.value = false
        loadPolicies()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        saving.value = false
      }
    }

    const handleSaveRoles = async () => {
      try {
        savingRoles.value = true
        ElMessage.success('角色分配成功')
        roleDialogVisible.value = false
      } catch (error) {
        ElMessage.error('角色分配失败')
      } finally {
        savingRoles.value = false
      }
    }

    const handleDelete = async (policy) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除策略 "${policy.name}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        ElMessage.success('策略删除成功')
        loadPolicies()
      } catch {
        // 用户取消
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      loadPolicies()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadPolicies()
    }

    onMounted(() => {
      loadPolicies()
      loadRoles()
    })

    return {
      loading,
      saving,
      savingRoles,
      policies,
      allRoles,
      searchKeyword,
      currentPage,
      pageSize,
      total,
      policyDialogVisible,
      roleDialogVisible,
      isEdit,
      currentPolicy,
      selectedRoles,
      policyForm,
      policyRules,
      filteredPolicies,
      showAddDialog,
      showEditDialog,
      showRoleDialog,
      handleSavePolicy,
      handleSaveRoles,
      handleDelete,
      handleSearch,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.attribute-policies-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 